package process;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import common.Resultat;
import dao_manager.UserInfoManager;
import dao_manager.UserInfoManagerImpl;
import ExceptionPerso.DupplicatedEntry;
import beans.UserRights;
import beans.user_Info;
import form.userForm;

public class ProcessNewUser extends Action {

    Logger l = LoggerFactory.getLogger( ProcessNewUser.class );
    
    public ProcessNewUser() {
        super();
    }

    @SuppressWarnings( "deprecation" )
    public ActionForward execute( ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response )
            throws Exception {

        ActionErrors errors=null;
        Resultat resultat;
        
        // save User in db and wait for teamleader accept
        // -------------------------------------------------------------------
        try
        {
            userForm userform = (userForm) form;
            user_Info user_info = new user_Info( userform );
            UserRights userRights = new UserRights( userform );
            
            
            UserInfoManager userInfoManager = new UserInfoManagerImpl();
            userInfoManager.saveNewUser( user_info, userRights );
            
            l.debug( " creation nouvel user -- id " + user_info.getUserName() + " id  "+ user_info.getId());
            resultat = Resultat.SUCCESS;
        } catch ( DupplicatedEntry e )
        {
            errors=new ActionErrors();
            errors.add( "dupplicated", new ActionMessage( "errors.ERROR_DUPPLICATION" ) );
            resultat=Resultat.ERROR_DUPPLICATION;
        }

        // ------------------------------------- le forwarding
        // ---------------------------------------

        if ( errors!=null ) {
            saveErrors( request, errors );
            return ( new ActionForward( mapping.getInput() ) );
        } else
        {
            
            return mapping.findForward( resultat.toString() );
            
        }
    }
}
